package com.linlong.linlongchat.handler;



import com.alibaba.fastjson.JSON;
import com.linlong.linlongchat.domain.po.Result;
import com.linlong.linlongchat.domain.websocket.data.Command;
import com.linlong.linlongchat.eee.CommandType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;


public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
        try{
            Command command = JSON.parseObject(frame.text(), Command.class);
            Integer commandCode = command.getCode();
            if (CommandType.CONNECTION.equals(CommandType.match(commandCode))) {
                ConnectionHandler.execute(ctx,command);
            } else if (CommandType.CHAT.equals(CommandType.match(commandCode))) {
               ChatHandler.execute(ctx,frame);
            }
            else if (CommandType.APPLY.equals(CommandType.match(commandCode))) {
                ApplyHandler.execute(ctx,frame);
            }else if (CommandType.APPLY_RESPONSE.equals(CommandType.match(commandCode))) {
                ApplyResponseHandler.execute(ctx,frame);
            }
            else {
                ctx.channel().writeAndFlush(Result.fail("不支持的CODE"));
            }
        } catch (Exception e) {
            ctx.channel().writeAndFlush(Result.fail(e.getMessage()));
        }

    }

}
